package com.walter.mail;

import com.walter.mail.configuration.MailProperties;
import com.walter.mail.param.MailParam;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 邮件发送服务类
 *
 * @author wuchenxi03
 * @date 2025/7/28
 */
@Component
public class MailService {

    @Inject
    private MailProperties mailProperties;

    /**
     * 发送简单文本邮件
     */
    public void sendSimpleMail(MailParam mailParam) throws MessagingException {
        sendSimpleMail(mailParam.getTo(), mailParam.getSubject(), mailParam.getContent(), mailProperties.getFrom());
    }

    /**
     * 发送简单文本邮件
     *
     * @param to      收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param from    发件人邮箱
     */
    private void sendSimpleMail(String to, String subject, String content, String from) throws MessagingException {
        Session session = createSession();

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, to);
        message.setSubject(subject, mailProperties.getEncoding());
        message.setText(content);
        message.setSentDate(new Date());

        Transport.send(message);
    }

    /**
     * 发送HTML格式邮件
     *
     */
    public void sendHtmlMail(MailParam mailParam) throws MessagingException {
        sendHtmlMail(mailParam.getTo(), mailParam.getSubject(), mailParam.getContent(), mailProperties.getFrom());
    }

    /**
     * 发送HTML格式邮件
     *
     * @param to      收件人邮箱
     * @param subject 邮件主题
     * @param content HTML格式邮件内容
     * @param from    发件人邮箱
     */
    private void sendHtmlMail(String to, String subject, String content, String from) throws MessagingException {
        Session session = createSession();

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, to);
        message.setSubject(subject, mailProperties.getEncoding());
        message.setContent(content, "text/html;charset=" + mailProperties.getEncoding());
        message.setSentDate(new Date());

        Transport.send(message);
    }

    /**
     * 发送带附件的邮件
     */
    public void sendAttachmentMail(MailParam mailParam) throws MessagingException {
        sendAttachmentMail(mailParam.getTo(), mailParam.getSubject(), mailParam.getContent(),
                mailProperties.getFrom(), mailParam.getAttachmentPaths());
    }

    /**
     * 发送带附件的邮件
     *
     * @param to               收件人邮箱
     * @param subject          邮件主题
     * @param content          邮件内容
     * @param from             发件人邮箱
     * @param attachmentPaths  附件路径列表
     */
    private void sendAttachmentMail(String to, String subject, String content, String from,
                                   List<String> attachmentPaths) throws MessagingException {
        Session session = createSession();

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, to);
        message.setSubject(subject, mailProperties.getEncoding());

        // 创建邮件正文
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(content);

        // 创建容器描述数据关系
        MimeMultipart multipart = new MimeMultipart();
        multipart.addBodyPart(textPart);

        // 添加附件
        if (attachmentPaths != null && !attachmentPaths.isEmpty()) {
            for (String attachmentPath : attachmentPaths) {
                File file = new File(attachmentPath);
                if (file.exists() && file.isFile()) {
                    try {
                        MimeBodyPart attachmentPart = new MimeBodyPart();
                        attachmentPart.attachFile(file);
                        multipart.addBodyPart(attachmentPart);
                    } catch (IOException e) {
                        throw new MessagingException("添加附件失败: " + attachmentPath, e);
                    }
                }
            }
        }

        message.setContent(multipart);
        message.setSentDate(new Date());

        Transport.send(message);
    }

    /**
     * 创建邮件会话
     *
     * @return Session
     */
    private Session createSession() {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", mailProperties.getHost());
        props.setProperty("mail.smtp.port", String.valueOf(mailProperties.getPort()));

        if (mailProperties.getSsl()) {
            props.setProperty("mail.smtp.ssl.enable", "true");
        }

        props.setProperty("mail.smtp.auth", "true");

        return Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(mailProperties.getUsername(), mailProperties.getPassword());
            }
        });
    }
}
